<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :close-on-click-modal="false"
    @close="handleClose" class="staff-dialog">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" class="staff-form">
      <!-- 姓名 -->
      <el-form-item label="姓名" prop="realname" required>
        <el-input v-model="formData.realname" placeholder="" />
      </el-form-item>

      <!-- 手机号 -->
      <el-form-item label="手机号" prop="mobile" required>
        <el-input v-model="formData.mobile" placeholder="" />
      </el-form-item>

      <!-- 所属部门 -->
      <el-form-item label="所属部门" prop="did" required>
        <el-select v-model="formData.did" filterable style="width: 100%">
          <el-option v-for="item in departmentOptions" :key="item.id" :label="item.dpname" :value="item.id">
            <span v-html="item.html" style="letter-spacing:6px"></span>
            {{ item.dpname }}
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 职位 -->
      <el-form-item label="职位" prop="role_id">
        <el-select v-model="formData.role_id" placeholder="请选择" filterable style="width: 100%">
          <el-option v-for="item in init_option?.role_option || []" :key="item.id" :label="item.role_name"
            :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <!-- 入职时间 -->
      <el-form-item label="入职时间" prop="addtime" v-if="formData.id">
        <el-input v-model="formData.addtime" :disabled="true" />
      </el-form-item>


    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>


</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { departmentApi } from '@/api/department'
import { checkIdCard } from '@/api/auth'
import isAuth from '@/common/isAuth'
import TOOLS from '@/utils/tools'

// 获取用户store和初始化选项
const userStore = useUserStore()
const init_option = userStore.init_option?.common_option || {}

// 调试信息
console.log('StaffDialog - userStore.init_option:', userStore.init_option)
console.log('StaffDialog - init_option:', init_option)
console.log('StaffDialog - role_option:', init_option?.role_option)

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  staffId: {
    type: [String, Number],
    default: ''
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  defaultDepartmentId: {
    type: [String, Number],
    default: ''
  }
})

// Emits
const emit = defineEmits(['update:visible', 'submit', 'cancel'])

// 响应式数据 
const formRef = ref()
const dialogVisible = ref(false)

// 上传相关数据
const uploadAction = ref(process.env.NODE_ENV === 'development' ? '/api/api/common/upload' : '/api/common/upload')
const uploadHeaders = ref({})
const idCardFileList = ref([])
const avatarFileList = ref([])

// 图片预览相关数据
const previewDialogVisible = ref(false)
const previewImageUrl = ref('')

// 部门选项
const departmentOptions = ref([])

// 默认表单数据结构
const getDefaultFormData = () => ({
  id: '',
  realname: '',
  mobile: '',
  did: '1',
  role_id: '',
  threshold: '',
  status: '0',
  rankname: '',
  id_card: '',
  pic: '',
  maturity: '',
  avatar: '',
  ...(isAuth('/is_total_threshold') && { total_threshold: '' })
})

// 表单数据
const formData = reactive(getDefaultFormData())

// 初始化部门选项
const initDepartmentOptions = () => {
  try {
    if (!userStore.init_option?.common_option) {
      console.warn('用户store中没有初始化选项，使用空数组')
      departmentOptions.value = []
      return
    }

    const departOption = userStore.init_option?.common_option?.depart_option || []
    departmentOptions.value = Array.isArray(departOption) && departOption.length > 0
      ? TOOLS.Flaten(departOption)
      : []
  } catch (error) {
    console.error('初始化部门选项失败:', error)
    departmentOptions.value = []
  }
}

// 表单验证规则
const formRules = {
  realname: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  did: [
    { required: true, message: '请选择所属部门', trigger: 'change' }
  ],
  threshold: [
    { required: true, message: '请输入日分配数据数', trigger: 'blur' }
  ],
  total_threshold: [
    { required: true, message: '请输入总阀值', trigger: 'blur' }
  ],
  id_card: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的18位身份证号', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return props.isEdit ? '编辑人员' : '添加人员'
})

// 监听 visible 变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    // 打开对话框时初始化数据
    initDepartmentOptions()
    initFormData()
  }
})

// 监听 dialogVisible 变化
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

// 初始化表单数据
const initFormData = async () => {
  if (props.isEdit && props.staffId) {
    // 编辑模式：根据ID获取员工详情
    await loadStaffDetails(props.staffId)
  } else {
    // 新增模式：重置表单数据
    resetFormData()
    // 如果有默认部门ID，设置为默认选中
    if (props.defaultDepartmentId) {
      formData.did = String(props.defaultDepartmentId)
    }
  }
}

// 获取员工详情
const loadStaffDetails = async (id) => {
  try {
    const response = await departmentApi.getStaffDetails({ id })
    if (response.status) {
      const staffData = response.data
      staffData.rankname = Number(staffData.rankname)

      Object.assign(formData, staffData)

      // 初始化文件列表
      initFileList()
    } else {
      ElMessage.error(response.msg || '获取员工详情失败')
      resetFormData()
    }
  } catch (error) {
    console.error('获取员工详情失败:', error)
    ElMessage.error('获取员工详情失败')
    resetFormData()
  }
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, getDefaultFormData())
  // 清空文件列表
  idCardFileList.value = []
  avatarFileList.value = []
}

// 创建文件对象的通用方法
const createFileObject = (url, name, uid) => ({
  name,
  url,
  uid,
  status: 'success',
  response: { name: url }
})

// 初始化文件列表
const initFileList = () => {
  // 初始化身份证照片列表
  idCardFileList.value = formData.pic
    ? formData.pic.split(',')
      .filter(url => url.trim())
      .map((url, index) => createFileObject(
        url.trim(),
        `身份证照片${index + 1}.jpg`,
        `id-card-${Date.now()}-${index}`
      ))
    : []

  // 初始化员工照片列表
  avatarFileList.value = formData.avatar
    ? [createFileObject(formData.avatar, '员工照片.jpg', `avatar-${Date.now()}`)]
    : []
}

// 事件处理
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const handleCancel = () => {
  emit('cancel')
  handleClose()
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()

    // 只提交指定的固定字段
    const submitData = {
      id: formData.id,
      realname: formData.realname,
      mobile: formData.mobile,
      did: formData.did,
      role_id: formData.role_id,
      threshold: formData.threshold,
      status: formData.status,
      rankname: formData.rankname,
      id_card: formData.id_card,
      pic: formData.pic,
      maturity: formData.maturity,
      avatar: formData.avatar
    }

    // 根据权限添加 total_threshold 字段
    if (isAuth('/is_total_threshold')) {
      submitData.total_threshold = formData.total_threshold || ''
    }

    emit('submit', submitData)
    handleClose()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const resetForm = () => {
  formRef.value?.resetFields()
}

// 身份证输入框失焦处理
const handleIdCardBlur = async () => {
  // 如果是编辑模式（有ID），则不进行验证
  if (formData.id) {
    return
  }

  // 调用身份证验证
  await validateIdCard()
}

// 身份证验证方法
const validateIdCard = async () => {
  if (!formData.id_card) {
    return
  }

  // 18位身份证正则验证
  const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/

  if (!idCardRegex.test(formData.id_card)) {
    ElMessage.error('请输入正确的18位身份证号')
    return
  }

  try {
    const response = await checkIdCard({ id_card: formData.id_card })
    if (!response.status) {
      ElMessageBox.alert(response.msg, '提示', {
        showCancelButton: false,
        showConfirmButton: false,
        type: 'warning'
      })
    }
  } catch (error) {
    console.error('身份证验证失败:', error)
    ElMessage.error('身份证验证失败，请重试')
  }
}

// 通用上传前检查
const beforeUpload = (file, type = 'image') => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error(`${type}只能是 JPG/PNG 格式!`)
    return false
  }
  if (!isLt2M) {
    ElMessage.error(`${type}大小不能超过 2MB!`)
    return false
  }
  return true
}

// 身份证照片上传前检查
const beforeIdCardUpload = (file) => beforeUpload(file, '身份证照片')

// 员工照片上传前检查
const beforeAvatarUpload = (file) => beforeUpload(file, '员工照片')

// 通用上传成功处理
const handleUploadSuccess = (response, file, type, fieldName) => {
  if (response.status) {
    ElMessage.success(`${type}上传成功`)

    if (fieldName === 'pic') {
      // 身份证照片支持多张
      if (formData.pic) {
        formData.pic += ',' + response.name
      } else {
        formData.pic = response.name
      }
    } else {
      // 员工照片只支持一张
      formData[fieldName] = response.name
    }

    // 更新文件对象的URL
    file.url = response.name
    file.response = response
  } else {
    ElMessage.error(response.msg || `${type}上传失败`)
  }
}

// 身份证照片上传成功
const handleIdCardUploadSuccess = (response, file) => {
  handleUploadSuccess(response, file, '身份证照片', 'pic')
}

// 员工照片上传成功
const handleAvatarUploadSuccess = (response, file) => {
  handleUploadSuccess(response, file, '员工照片', 'avatar')
}

// 上传失败处理
const handleUploadError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('上传失败，请重试')
}

// 通用超出限制处理
const handleUploadExceed = (message) => {
  ElMessage.warning(message)
}

// 身份证照片超出限制处理
const handleExceed = () => handleUploadExceed('最多只能上传5张身份证照片')

// 员工照片超出限制处理
const handleAvatarExceed = () => handleUploadExceed('只能上传1张员工照片，请先删除现有照片')

// 身份证照片删除处理
const handleIdCardRemove = (file, fileList) => {
  try {
    if (formData.pic) {
      const fileUrlToRemove = file.url || file.response?.name || ''
      const filteredUrls = formData.pic
        .split(',')
        .filter(url => url.trim() && url.trim() !== fileUrlToRemove)

      formData.pic = filteredUrls.join(',')
    }

    // 更新文件列表
    idCardFileList.value = [...fileList]
  } catch (error) {
    console.error('删除身份证照片失败:', error)
    ElMessage.error('删除照片失败')
  }
}

// 员工照片删除处理
const handleAvatarRemove = (_, fileList) => {
  // 清空表单数据中的头像URL
  formData.avatar = ''
  // 更新文件列表
  avatarFileList.value = [...fileList]
}

// 通用图片预览处理
const handleImagePreview = (file) => {
  if (file.url) {
    previewImageUrl.value = file.url
    previewDialogVisible.value = true
  }
}

// 身份证照片预览处理
const handleIdCardPreview = handleImagePreview

// 员工照片预览处理
const handleAvatarPreview = handleImagePreview
</script>

<style scoped>
.staff-dialog :deep(.el-dialog__header) {
  background-color: #f8f9fa;
  padding: 15px 20px;
  border-bottom: 1px solid #e9ecef;
}

.staff-dialog :deep(.el-dialog__title) {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.staff-form {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

/* 统一字体大小和样式 */
.staff-form :deep(.el-form-item__label) {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
  font-weight: 500;
}

.staff-form :deep(.el-input__inner),
.staff-form :deep(.el-select .el-input__inner),
.staff-form :deep(.el-textarea__inner),
.staff-form :deep(.el-option),
.staff-form :deep(.el-radio__label),
.staff-form :deep(.el-radio__input),
.staff-form :deep(.el-button) {
  font-size: 14px;
}

.staff-form :deep(.el-input__inner),
.staff-form :deep(.el-select .el-input__inner),
.staff-form :deep(.el-textarea__inner) {
  border-radius: 4px;
}

.staff-form :deep(.el-form-item) {
  margin-bottom: 18px;
}

.staff-form :deep(.el-radio-group) {
  display: flex;
  gap: 20px;
}

.staff-form :deep(.el-radio__label) {
  color: #606266;
}

.form-note {
  font-size: 13px;
  color: var(--theme-text-secondary);
  margin-top: 4px;
  line-height: 1.4;
}

/* 上传组件样式 */
.upload-icon {
  font-size: 28px;
  color: var(--theme-text-secondary);
  transition: color 0.3s ease;
}

.upload-icon:hover {
  color: #4a90e2;
}

:deep(.el-upload) {
  border: 1px dashed var(--theme-border-base);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

:deep(.el-upload:hover) {
  border-color: var(--theme-primary);
}

:deep(.el-upload-list__item) {
  transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
}

:deep(.el-upload-list__item-name),
:deep(.el-upload__tip) {
  color: #606266;
  font-size: 12px;
}

:deep(.el-upload__tip) {
  margin-top: 7px;
}

/* 图片预览样式 */
:deep(.el-upload-list--picture-card .el-upload-list__item),
:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  border-radius: 6px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  margin: 0 8px 8px 0;
}

/* 图片预览对话框样式 */
.preview-container {
  text-align: center;
  padding: 20px;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 0 20px 20px;
}

/* 自定义滚动条 */
.staff-form::-webkit-scrollbar {
  width: 6px;
}

.staff-form::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.staff-form::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.staff-form::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
